package biz

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	recover_v1 "kratosRecoverPanic/api/recover/v1"
	"time"
)

type RecoverBiz struct {
	log     *log.Helper
	baseBiz *BaseBiz
	// TODO 如果有操作 DB/redis 可以加上repo 并在data层定义自己的repo(封装data——>data中再初始化下DB与redis)
}

func NewRecoverBiz(logger log.Logger, baseBiz *BaseBiz) *RecoverBiz {
	return &RecoverBiz{
		log:     log.NewHelper(logger),
		baseBiz: baseBiz,
	}
}

func (r *RecoverBiz) KratosRecover(ctx context.Context, req *recover_v1.KratosRecoverReq) (*recover_v1.KratosRecoverReply, error) {
	ctx, span := otel.Tracer("BIZ").Start(ctx, "KratosRecoverBiz", trace.WithSpanKind(trace.SpanKindInternal))
	defer span.End()

	// 1、主协程中发生了panic
	panic(123)

	// 2、子协程中发生了panic
	//go r.tsSonGTRecover(ctx)

	reply := &recover_v1.KratosRecoverReply{
		Reply: fmt.Sprintf("请求的参数是: %v", req.GetReq()),
	}

	time.Sleep(time.Second)

	return reply, nil
}

func (r *RecoverBiz) tsSonGTRecover(ctx context.Context) {
	ctx, span := otel.Tracer("BIZ").Start(ctx, "tsSonGTRecover", trace.WithSpanKind(trace.SpanKindInternal))
	defer func() {
		//if err := recover(); err != nil {
		//	// trace
		//	stackInfo := string(debug.Stack())
		//	span.SetAttributes(attribute.String("errStack", stackInfo))
		//	// log
		//	errMsg := fmt.Sprintf("%v方法中发生了panic errStack: %v", "KratosRecoverService", stackInfo)
		//	r.log.WithContext(ctx).Error(errMsg)
		//}
		span.End()
	}()

	// 子协程中发生了 panic
	panic("tsSonGTRecover")

}
